<template>
  <div>
    <h1>图书管理系统</h1>
    <div class="mb-4">
      <el-button type="primary" plain @click="openAddDialog">添加图书</el-button>
    </div>

    <el-dialog v-model="addBookFormVisible" :title="dialogTitle" width="500">
      <el-form :model="form">
        <el-form-item label="编号" :label-width="formLabelWidth">
          <el-input v-model="form.book_number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="书名" :label-width="formLabelWidth">
          <el-input v-model="form.book_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="作者" :label-width="formLabelWidth">
          <el-input v-model="form.author" autocomplete="off" />
        </el-form-item>
        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="form.book_price" autocomplete="off" />
        </el-form-item>
        <el-form-item label="出版社" :label-width="formLabelWidth">
          <el-input v-model="form.book_press" autocomplete="off" />
        </el-form-item>
        <el-form-item label="出版日期" :label-width="formLabelWidth">
          <el-date-picker v-model="form.publication_date" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-input v-model="form.book_type" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addBookFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">{{ dialogMode.value === 'add' ? '确认添加' : '确认修改'
            }}</el-button>
        </div>
      </template>
    </el-dialog>

    <el-table :data="filterTableData" style="width: 100%">
      <el-table-column label="编号" prop="book_number" />
      <el-table-column label="书名" prop="book_name" />
      <el-table-column label="作者" prop="author" />
      <el-table-column label="价格" prop="book_price" />
      <el-table-column label="出版社" prop="book_press" />
      <el-table-column label="出版日期" prop="publication_date" />
      <el-table-column label="类型" prop="book_type" />
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="Type to search" />
        </template>
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            Edit
          </el-button>
          <el-button size="small" type="danger" @click="confirmDelete(scope.$index, scope.row)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

interface Book {
  id?: number; // 图书的唯一标识符
  author: string;
  book_name: string;
  book_number: string;
  book_press: string;
  book_price: number;
  book_type: string;
  publication_date: string;
}

// 表单数据
const form = reactive<Book>({
  book_number: '',
  book_name: '',
  author: '',
  book_price: 0,
  book_press: '',
  publication_date: '',
  book_type: '',
});

// 用于控制对话框显示/隐藏
const addBookFormVisible = ref(false);

// 对话框的模式：添加或编辑
const dialogMode = ref<'add' | 'edit'>('add');

// 对话框标题，根据模式动态更新
const dialogTitle = computed(() => (dialogMode.value === 'add' ? '添加图书' : '编辑图书'));

// 表单标签宽度
const formLabelWidth = ref('120px');

// 图书数据
const books = reactive<Book[]>([]);

// 搜索框绑定值
const search = ref('');

// 过滤后的图书数据
const filterTableData = computed(() =>
  books.filter(
    (data) =>
      !search.value ||
      data.book_name.toLowerCase().includes(search.value.toLowerCase())
  )
);

// 重置表单
const resetForm = () => {
  form.book_number = '';
  form.book_name = '';
  form.author = '';
  form.book_price = 0;
  form.book_press = '';
  form.publication_date = '';
  form.book_type = '';
};

// 获取图书数据
const getBooks = async () => {
  try {
    const res = await axios.get('http://localhost:5000/books/');
    books.splice(0, books.length, ...res.data.results);
  } catch (error) {
    console.error('获取书籍数据失败:', error);
  }
};

// 打开添加图书对话框
const openAddDialog = () => {
  dialogMode.value = 'add';
  resetForm();
  addBookFormVisible.value = true;
};

// 点击确认按钮时的逻辑
const handleConfirm = () => {
  if (dialogMode.value === 'add') {
    addBook();
  } else if (dialogMode.value === 'edit') {
    editBook();
  }
};

// 添加图书
const addBook = () => {
  console.log(form)
  axios.post('http://localhost:5000/books/', form)
    .then(() => {
      getBooks(); // 更新列表
      ElMessage({ type: 'success', message: '图书添加成功' });
      addBookFormVisible.value = false;
      // form.resetFields();
      resetForm();
    })
    .catch(error => {
      console.error('添加书籍失败:', error);
      ElMessage({ type: 'error', message: '图书添加失败' });
    });
};
// 编辑图书
const editBook = () => {
  if (!form.id) {
    ElMessage({ type: 'error', message: '未找到要编辑的书籍ID' });
    return;
  }
  axios.put(`http://localhost:5000/books/${form.id}`, form)
    .then(() => {
      getBooks(); // 更新列表
      ElMessage({ type: 'success', message: '图书修改成功' });
      addBookFormVisible.value = false;
      resetForm();
    })
    .catch(error => {
      console.error('修改书籍失败:', error);
      ElMessage({ type: 'error', message: '图书修改失败' });
    });
};

// 编辑图书时打开对话框
const handleEdit = (index: number, row: Book) => {
  dialogMode.value = 'edit';
  Object.assign(form, row); // 填充表单
  addBookFormVisible.value = true;
};

// 删除图书
const confirmDelete = (index: number, row: Book) => {
  ElMessageBox.confirm('是否永久删除该书籍', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteBook(row.id);
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除' });
    });
};

const deleteBook = (id: number) => {
  axios.delete(`http://localhost:5000/books/${id}`)
    .then(() => {
      getBooks(); // 更新列表
      ElMessage({ type: 'success', message: '删除成功' });
    })
    .catch(error => {
      console.error('删除书籍失败:', error);
      ElMessage({ type: 'error', message: '删除失败' });
    });
};

// 初始化时获取图书列表
onMounted(() => {
  getBooks();
});
</script>

<style scoped></style>